﻿Imports System.IO
Imports System.ServiceProcess
Imports System.Xml
Imports System.Xml.XPath

Public Class frmTray

#Region "Listview header class"
    Private Declare Function GetWindow Lib "user32" Alias "GetWindow" (ByVal hwnd As IntPtr, ByVal wCmd As Integer) As IntPtr
    Private Const GW_CHILD As Integer = 5
    Private SysHdr32Handle As IntPtr
    Private Class ListViewHeader
        Inherits System.Windows.Forms.NativeWindow
        Private ptrHWnd As IntPtr
        Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
            Select Case m.Msg
                Case Is = &H20  ' WM_SETCURSOR
                    m.Msg = 0
                Case Is = &H201  ' WM_LBUTTONDOWN
                    m.Msg = 0
            End Select
            MyBase.WndProc(m)
        End Sub
        Protected Overrides Sub Finalize()
            Me.ReleaseHandle()
            MyBase.Finalize()
        End Sub
        Public Sub New(ByVal ControlHandle As IntPtr)
            ptrHWnd = ControlHandle
            Me.AssignHandle(ptrHWnd)
        End Sub
    End Class
    Private lvHeader As ListViewHeader
#End Region
#Region "Form events and handling"
    Public selClient As New clsClientConfiguration.clsClientConfigs.sClientSettings.sClient
    Public _scTS As TimeSpan = TimeSpan.FromSeconds(0)
    Public _scDT As DateTime = #1/1/2000#
    Private mSize As System.Drawing.Size, mSizeM As System.Drawing.Size
    Private sSize As System.Drawing.Size
    Public _NoUpdate As Boolean = True
    Private _OldSettings As Boolean = False
    Private _lvcMenuIndex As Int16 = -1
    Private WithEvents lvMenu As New ContextMenuStrip
    'Normal timers?
    Private tUpdating As Boolean = True
    Public tUpdates() As System.Timers.Timer
    Public tAP As System.Timers.Timer
    Public ReadOnly Property sClient() As clsClientConfiguration.clsClientConfigs.sClientSettings.sClient
        Get
            Return selClient
        End Get
    End Property
    Private Sub frmTray_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
        If Me.WindowState = FormWindowState.Minimized Then
            tDT.Enabled = False
            nIcon.Visible = True
            Me.ShowInTaskbar = False
        Else
            tDT.Enabled = True
            nIcon.Visible = False
            Me.ShowInTaskbar = True
        End If
    End Sub
    Private Sub ResizeLVC()
        fTray.lvC.Dock = DockStyle.None
        fTray.lvC.Width = 10
        fTray.lvC.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize)
        For xInd As Int16 = 0 To fTray.lvC.Columns.Count - 1
            mySettings.HeaderWidth(xInd) = fTray.lvC.Columns(xInd).Width
        Next
        fTray.lvC.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
        'if content is smaller then header, then resize that collum back
        For xInd As Int16 = 0 To fTray.lvC.Columns.Count - 1
            If fTray.lvC.Columns(xInd).Width < mySettings.HeaderWidth(xInd) Then fTray.lvC.AutoResizeColumn(xInd, ColumnHeaderAutoResizeStyle.HeaderSize)
        Next
        fTray.lvC.Dock = DockStyle.Fill
    End Sub
    Private Sub frmTray_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
        Try
            tPB.Width = Me.ClientSize.Width - tsTime.Width - tsTotalPPD.Width - 100
            If mySettings.bStartClients Then
                For xInt As Int16 = 1 To Clients.GetUpperBound(0)
                    If Clients(xInt).PandeGroup.ServiceMode Then
                        If Clients(xInt).GuiController.ServiceState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eServiceState.Stopped Then
                            Clients(xInt).GuiController.StartClient()
                            WaitMS(500)
                        ElseIf Clients(xInt).GuiController.ServiceState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eServiceState.Paused Then
                            Clients(xInt).GuiController.ContinueClient()
                            WaitMS(500)
                        End If
                    Else
                        If Clients(xInt).GuiController.Running(True) = False Then Clients(xInt).GuiController.StartClient()
                        WaitMS(500)
                    End If
                Next
            End If
            'Start watching clients
            If mySettings.bAutoReload Then
                For xInd As Int16 = 1 To Clients.GetUpperBound(0)
                    Clients(xInd).GuiController.StartWatching()
                Next
            End If
            If mySettings.bStartInTray Then
                fTray.WindowState = FormWindowState.Minimized
            Else
                fTray.WindowState = FormWindowState.Normal
                With fTray
                    .lvC.Items(0).Selected = True
                    .selClient = Clients(1)
                    If mySettings.bExtendGUI Then
                        .tQueueTimeout_Tick(fTray, Nothing)
                        .tLogTimeout_Tick(fTray, Nothing)
                    End If
                End With
            End If
        Catch ex As Exception

        End Try
    End Sub
    Public Sub ShowMe()
        nIcon.Visible = False
        If lvC.SelectedItems.Count = 0 Then
            lvC.Items(0).Selected = True
            selClient = Clients(1)
        End If
        If mySettings.bExtendGUI Then
            tQueueTimeout_Tick(fTray, Nothing)
            tLogTimeout_Tick(fTray, Nothing)
        End If
        Me.WindowState = FormWindowState.Normal
        Me.ShowInTaskbar = True
        Me.Show()
        tDT.Enabled = True
    End Sub
    Private Sub nIcon_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles nIcon.MouseClick
        If e.Button = Windows.Forms.MouseButtons.Left Then ShowMe()
    End Sub
    Private Sub nIcon_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles nIcon.MouseDoubleClick
        If e.Button = Windows.Forms.MouseButtons.Left Then ShowMe()
    End Sub
    Private Sub lvMenu_ItemClicked(ByVal sender As Object, ByVal e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles lvMenu.ItemClicked
        Try
            If _lvcMenuIndex = -1 Then Exit Sub
            Select Case e.ClickedItem.Text
                Case "Pause"
                    Clients(_lvcMenuIndex).GuiController.PauseClient()
                Case "Continue"
                    Clients(_lvcMenuIndex).GuiController.ContinueClient()
                Case "Stop"
                    Clients(_lvcMenuIndex).GuiController.StopClient()
                Case "Start"
                    If Not mnuStopWhenDone.Checked Then
                        Clients(_lvcMenuIndex).GuiController.StartClient()
                    Else
                        Clients(_lvcMenuIndex).GuiController.StartClient("-oneunit")
                    End If
                Case "Show"
                    Clients(_lvcMenuIndex).GuiController.ShowConsole()
                Case "Hide"
                    Clients(_lvcMenuIndex).GuiController.HideConsole()
                Case "Show files"
                    Process.Start(Clients(_lvcMenuIndex).GuiController.ClientLocation)
                Case "Configure"
                    Cfg.CfgManager.ClientSettings.ShowConfig(Clients(_lvcMenuIndex))
                Case "Show Queue"
                    Dim fQueue As New frmQueue
                    fQueue.ShowQueue(Clients(_lvcMenuIndex), fTray)
                Case "Send all"
                    If Clients(_lvcMenuIndex).GuiController.SendAll Then
                        AddHandler Clients(_lvcMenuIndex).GuiController.SendAllDone, AddressOf SendAllResults
                    Else
                        'Log to window/show message?
                    End If
                Case "Show stats"
                    Dim nStats As New frmEOC
                    If nStats.ShowSig(Clients(_lvcMenuIndex)) Then
                        fTray.Focus()
                        Clients(_lvcMenuIndex).GuiController.StatsVisible = True
                        Clients(_lvcMenuIndex).GuiController.StatsForm = nStats
                    End If
                Case "Close stats"
                    Clients(_lvcMenuIndex).GuiController.StatsForm.Close()
                    Clients(_lvcMenuIndex).GuiController.StatsVisible = False
            End Select
        Catch ex As Exception

        End Try
    End Sub
    Private Sub lvC_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lvC.MouseDown
        'Get the client at the location!
        Try
            If e.Button = Windows.Forms.MouseButtons.Right Then
                Dim lhi As ListViewHitTestInfo = lvC.HitTest(e.X, e.Y)
                If lhi.Item.Index <> -1 Then
                    _lvcMenuIndex = lhi.Item.Index + 1
                    lvMenu.Items.Clear()
                    With Clients(_lvcMenuIndex).GuiController
                        If Clients(_lvcMenuIndex).PandeGroup.ServiceMode Then
                            Select Case Clients(_lvcMenuIndex).GuiController.ServiceState
                                Case clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eServiceState.Err
                                    'Add code for error reporting
                                Case clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eServiceState.Paused
                                    lvMenu.Items.Add("Continue")
                                    lvMenu.Items.Add("Stop")
                                Case clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eServiceState.Running
                                    lvMenu.Items.Add("Stop")
                                    lvMenu.Items.Add("Pause")
                                Case clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eServiceState.Stopped
                                    lvMenu.Items.Add("Start")
                            End Select
                        Else
                            If .Running(True) Then
                                lvMenu.Items.Add("Stop")
                            Else
                                lvMenu.Items.Add("Start")
                            End If
                        End If
                        If .wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Visible Then
                            lvMenu.Items.Add("Hide")
                        ElseIf .wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Hidden Then
                            lvMenu.Items.Add("Show")
                        End If
                        lvMenu.Items.Add("Configure")
                        If .Queue.WUs_Ready > 0 Then
                            If .bSendAllBussy Then
                                lvMenu.Items.Add("Send all bussy..")
                            Else
                                lvMenu.Items.Add("Send all")
                            End If
                        End If
                        lvMenu.Items.Add("-")
                        If Clients(_lvcMenuIndex).GuiController.StatsVisible Then
                            lvMenu.Items.Add("Close stats")
                        Else
                            lvMenu.Items.Add("Show stats")
                        End If
                        lvMenu.Items.Add("Show Queue")
                        lvMenu.Items.Add("Show files")
                    End With
                    lvMenu.Show(lvC, e.X, e.Y)
                    Exit Sub
                End If
                _lvcMenuIndex = -1
            Else
                Dim lhi As ListViewHitTestInfo = lvC.HitTest(e.X, e.Y)
                If lhi.Item.Index <> -1 Then
                    selClient = Clients(lhi.Item.Index + 1)
                    lhi.Item.Selected = True
                    Application.DoEvents()
                    tQueueTimeout_Tick(Me, Nothing)
                    tLogTimeout_Tick(Me, Nothing)
                    Call tDT_Tick(Me, Nothing)
                End If
            End If
        Catch ex As Exception

        End Try
    End Sub
    Private Sub SendAllResults(ByVal Client As clsClientConfiguration.clsClientConfigs.sClientSettings.sClient)
        Try
            With Client.GuiController
                Select Case .SendAllResults
                    Case clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eSendAllResults.AllSend
                        MsgBox(.ShortName & " has send all completed work units")
                    Case clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eSendAllResults.Err
                        MsgBox(.ShortName & " could not send any work units due to an application error")
                    Case clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eSendAllResults.NoneSend
                        MsgBox(.ShortName & " was not able to send any completed work units to the servers")
                    Case clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eSendAllResults.SomeSend
                        MsgBox(.ShortName & " has send some completed work units to the servers")
                End Select
            End With
            RemoveHandler Client.GuiController.SendAllDone, AddressOf SendAllResults
        Catch ex As Exception
            LogWindow.WriteError("fTray, SendAllResults", Err)
        End Try
    End Sub
    Public Sub SetFormSize()
        Try
            Me.Visible = False
            If mySettings.bExtendGUI Then
                scClLo.Panel2Collapsed = False
                scMain.Panel2Collapsed = False
                If lvC.SelectedItems.Count = 0 Then
                    lvC.Items(0).Selected = True
                    Call tLogTimeout_Tick(Me, Nothing)
                    Call tQueueTimeout_Tick(Me, Nothing)
                    Application.DoEvents()
                End If
                Me.Size = mSize
                Dim iFHeight As Int16 = My.Resources.TRFFC10A.Height - 2
                If lvC.Items.Count = 1 Then
                    lvC.Height = ((lvC.Items.Count + 2) * iFHeight + 2)
                Else
                    lvC.Height = (lvC.Items.Count * iFHeight)
                End If
                scClLo.SplitterDistance = lvC.Height
            Else    'hide log
                scClLo.Panel2Collapsed = True
                scMain.Panel2Collapsed = True
                Me.Size = sSize
            End If
            Me.Refresh()
            Me.Visible = True
        Catch ex As Exception
            Debug.Print(ex.Message)
            Me.Visible = True
        End Try
    End Sub
    Private iSplitter As Int16 = 0
    Private _ilvcHeaderHeight As Int16
    Public Sub Prepare()
        Try
            scClLo.Panel2Collapsed = False  'Show log/progressbar
            scMain.Panel2Collapsed = False  'Show wu info panel
            'undock all
            Panel1.Dock = DockStyle.None
            scMain.Dock = DockStyle.None
            scMain.FixedPanel = FixedPanel.None
            scClLo.Dock = DockStyle.None
            lvC.Dock = DockStyle.None
            'Get LVC width, sSize.width, scMain.splitterdistance                
            Dim ilvC_width As Integer = 0
            Dim iMainWidth As Integer = 0
            Dim iMainSplitterDistance As Integer = 0
            Dim iCLLOSplitterDistance As Integer = 0
            For xInd As Int16 = 0 To lvC.Columns.Count - 1
                ilvC_width += lvC.Columns(xInd).Width + 1 '+1 for border between columns?
            Next
            iMainWidth = ilvC_width + (Me.Size.Width - Me.ClientSize.Width) 'main width = form width for minimal view
            sSize.Width = iMainWidth
            iSplitter = ilvC_width
            scMain.SplitterDistance = ilvC_width
            'Get LVC height, sSize.height
            Dim iFHeight As Int16 = My.Resources.TRFFC10A.Height - 2
            If lvC.Items.Count = 1 Then
                lvC.Height = ((lvC.Items.Count + 2) * iFHeight + 2)
            Else
                lvC.Height = (lvC.Items.Count * iFHeight)
            End If
            scClLo.SplitterDistance = lvC.Height
            sSize.Height = lvC.Height + (Me.Size.Height - Me.ClientSize.Height)
            sSize.Height = lvC.Height + (Me.Size.Height - Me.ClientSize.Height)
            'Set scMain.width
            scMain.Width = scMain.SplitterDistance + scMain.SplitterWidth + scMain.Panel2MinSize
            'Set spClientsEOC.heigh
            'Dock everything
            Panel1.Dock = DockStyle.Fill
            scMain.Dock = DockStyle.Fill
            scClLo.Dock = DockStyle.Fill
            lvC.Dock = DockStyle.Fill
            'Set fixed panels
            scMain.FixedPanel = FixedPanel.Panel1
            mSize.Width = sSize.Width + scMain.SplitterWidth + 330   '325 for panel2 
            mSize.Height = 700 'Random
        Catch ex As Exception
            Debug.Print(ex.Message)
        End Try
    End Sub
    Private Sub frmTray_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Try
            If Not e.CloseReason = CloseReason.WindowsShutDown And mySettings.bConfirmExit And Not _bExit Then
                Dim rVal As MsgBoxResult = MsgBox("Exit maxTray?", MsgBoxStyle.OkCancel + MsgBoxStyle.Question, "Confirm exit")
                If rVal = MsgBoxResult.Cancel Then
                    e.Cancel = True
                    Exit Sub
                End If
            End If
            For xInt As Int16 = 1 To Clients.GetUpperBound(0)
                Clients(xInt).GuiController.HideIcon()
                If Clients(xInt).GuiController.StatsVisible Then Clients(xInt).GuiController.StatsForm.Close()
                If mySettings.bShowConsolesOnExit And Clients(xInt).GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Hidden Then Clients(xInt).GuiController.ShowConsole()
            Next
            nIcon.Visible = False
        Catch ex As Exception

        End Try
    End Sub
    Private Sub frmTray_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            Me.Visible = False
            SysHdr32Handle = GetWindow(lvC.Handle, GW_CHILD)
            lvHeader = New ListViewHeader(SysHdr32Handle)
            Me.Text = "maxTray " & Application.ProductVersion
            tsTime.Text = DateTime.Now.ToShortDateString & " " & DateTime.Now.ToLongTimeString
            Prepare()
            SetFormSize()
            'Add timers for each client to a new invisible panel?
            ReDim tUpdates(0 To Clients.GetUpperBound(0))
            For xInd As Int16 = 1 To Clients.GetUpperBound(0)
                tUpdates(xInd) = New System.Timers.Timer
                tUpdates(xInd).AutoReset = False 'prevent the timer from firing twice if the handler sub doesn't disable it in time
                AddHandler tUpdates(xInd).Elapsed, AddressOf tUpdateClient
            Next
            rtLOG.MaxLength = Int32.MaxValue
            'menu's
            tAP = New System.Timers.Timer
            Dim lInterval As Long = mySettings.iAPinterval * 60 * 1000
            tAP.Interval = lInterval
            AddHandler tAP.Elapsed, AddressOf tAP_Tick
            If mySettings.bManualAP Then Call tAP_Tick()
            Me.Visible = True
            _NoUpdate = False
        Catch ex As Exception
            LogWindow.WriteError("fTray, Load()", Err)
        End Try
    End Sub
    Public Function SetAPinterval(ByVal Miliseconds As Long) As Boolean
        Try
            tAP.Enabled = False
            tAP.Interval = Miliseconds
            Call tAP_Tick()
        Catch ex As Exception

        End Try
    End Function
    Private Sub tAP_Tick()
        Try
            tAP.Enabled = False
            For xInt As Int16 = 1 To Clients.GetUpperBound(0)
                If Clients(xInt).GuiController.GetWorkers Then
                    Clients(xInt).GuiController.ApplyAP()
                End If
            Next
            tAP.Enabled = mySettings.bManualAP
        Catch ex As Exception

        End Try
    End Sub
    Private Sub rtLOG_LinkClicked(ByVal sender As Object, ByVal e As System.Windows.Forms.LinkClickedEventArgs)
        Process.Start(e.LinkText)
    End Sub
#End Region
#Region "Log and Queu parsing"
    Delegate Sub uTV()
    Delegate Sub uClient(ByVal Client As clsClientConfiguration.clsClientConfigs.sClientSettings.sClient)
    Public Delegate Sub lSafe()
    Public Delegate Sub qSafe()
    Public Sub ReadLOG()
        Try
            Dim tSafe As New lSafe(AddressOf rLogSafe)
            Me.Invoke(tSafe)
        Catch ex As Exception
            'MsgBox(ex.Source & vbNewLine & ex.Message & vbNewLine & ex.InnerException.Message & vbNewLine)
        End Try
    End Sub
    Public Sub ReadQueue()
        Try
            'Read qeueu.dat
            Dim rSafe As New qSafe(AddressOf rQueSafe)
            Me.Invoke(rSafe)
        Catch ex As Exception
            'MsgBox(ex.Source & vbNewLine & ex.Message & vbNewLine & ex.InnerException.Message & vbNewLine)
        End Try
    End Sub
    Public Sub rLogSafe()
        Try
            If tLogTimeout.Enabled Then
                Exit Sub
            Else
                tLogTimeout.Enabled = True
            End If
        Catch ex As Exception

        End Try
    End Sub
    Public Sub rQueSafe()
        Try
            If tQueueTimeout.Enabled Then
                Exit Sub
            Else
                tQueueTimeout.Enabled = True
            End If
        Catch ex As Exception

        End Try
    End Sub
    Public Sub UCinvoked(ByVal Client As clsClientConfiguration.clsClientConfigs.sClientSettings.sClient)
        Try
            If tUpdates(Client.Index).Enabled Then
                Exit Sub
            Else
                tUpdates(Client.Index).Interval = 500
                tUpdates(Client.Index).Enabled = True
            End If
        Catch ex As Exception

        End Try
    End Sub
    Public Sub UpdateClientInvoked(ByVal uClient As clsClientConfiguration.clsClientConfigs.sClientSettings.sClient)
        Dim tSafe As New uClient(AddressOf UCinvoked)
        Me.Invoke(tSafe, New Object() {uClient})
    End Sub
#End Region
#Region "Menu strips"
    Private _bExit As Boolean = False
    Private Sub mnuExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuExit.Click
        If mySettings.bConfirmExit Then
            Dim rVal As MsgBoxResult = MsgBox("Exit maxTray?", MsgBoxStyle.OkCancel + MsgBoxStyle.Question, "Confirm exit")
            If rVal = MsgBoxResult.Cancel Then Exit Sub
        End If
        _bExit = True
        Me.Close()
    End Sub
    Private Sub mnuDownloadProjects_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuDownloadProjects.Click
        Try
            Dim dThread As New Threading.Thread(AddressOf DoDownload)
            dThread.Start()
        Catch ex As Exception

        End Try
    End Sub
    Private Sub DoDownload()
        ProjectInfo.GetProjects()
    End Sub
    Private Sub mnuProjectBrowser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuProjectBrowser.Click
        If ProjectInfo.ProjectCount = 0 Then ProjectInfo.GetProjects()
        If selClient.GuiController.Queue.FullSlots Then
            If ProjectInfo.KnownProject(selClient.GuiController.CurrentProject.Project.Project) Then
                fPrBrowse.ShowBrowser(Me, selClient.GuiController.CurrentProject.Project.Project)
            Else
                fPrBrowse.ShowBrowser(Me)
            End If
        Else
            fPrBrowse.ShowBrowser(Me)
        End If
    End Sub
    Private Sub CloseToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuClose.Click
        Me.Close()
    End Sub
    Private Sub ShowToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuShow.Click
        ShowMe()
    End Sub
    Private Sub mnuMinimize_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuMinimize.Click
        Me.WindowState = FormWindowState.Minimized
    End Sub
    Private Sub ManualRefreshToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuRefreshAll.Click
        For xInd As Integer = 1 To Clients.GetUpperBound(0)
            UpdateClientInvoked(Clients(xInd))
        Next
        Exit Sub
    End Sub
    Private Sub StopAllToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuAllStop.Click
        For xInd As Integer = 1 To Clients.GetUpperBound(0)
            Clients(xInd).GuiController.StopClient()
            Clients(xInd).GuiController.StopWatching()
        Next
        If lvC.SelectedItems.Count = 0 Then selClient = Clients(1)
        ReadLOG()
        ReadQueue()
    End Sub
    Private Sub StartAllToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuAllStart.Click
        For xInd As Integer = 1 To Clients.GetUpperBound(0)
            If Not Clients(xInd).GuiController.Running(True) Then
                If mnuStopWhenDone.Checked Then
                    Clients(xInd).GuiController.StartClient("-oneunit")
                Else
                    Clients(xInd).GuiController.StartClient()
                End If
                If mySettings.bAutoReload Then Clients(xInd).GuiController.StartWatching()
            End If
        Next
    End Sub
    Private Sub HideAllClientsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuAllHide.Click
        For xInd As Integer = 1 To Clients.GetUpperBound(0)
            Clients(xInd).GuiController.HideConsole()
        Next
    End Sub
    Private Sub ShowAllClientsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuAllShow.Click
        For xInd As Integer = 1 To Clients.GetUpperBound(0)
            Clients(xInd).GuiController.ShowConsole()
        Next
    End Sub
    Private Sub bExtend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuExtend.Click
        mySettings.bExtendGUI = mnuExtend.Checked
        SetFormSize()
    End Sub
    Private Sub mnuEOC_Forum_Click(ByVal Sender As Object, ByVal e As System.EventArgs) Handles mnuEOC_forum.Click
        Try
            Process.Start("http://forums.extremeoverclocking.com/forumdisplay.php?f=45")
        Catch ex As Exception

        End Try
    End Sub
    Private Sub mnuEOC_Stats_Click(ByVal Sender As Object, ByVal e As System.EventArgs) Handles mnuEOC_Stats.Click
        Try
            Process.Start("http://folding.extremeoverclocking.com/team_list.php?s=")
        Catch ex As Exception

        End Try
    End Sub
    Private Sub FoldingForumToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuFoldingForum.Click
        Try
            Process.Start("http://foldingforum.org/index.php")
        Catch ex As Exception

        End Try
    End Sub
    Private Sub llblName_LinkClicked(ByVal sender As Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles llblName.LinkClicked
        Try
            Process.Start("http://folding.extremeoverclocking.com/user_summary.php?s=&u=" & selClient.GuiController.EOCStats.LastUpdate.User.UserID)
        Catch ex As Exception

        End Try
    End Sub
    Private Sub llblTeam_LinkClicked(ByVal sender As Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles llblTeam.LinkClicked
        Try
            Process.Start("http://folding.extremeoverclocking.com/team_summary.php?s=&t=" & selClient.PandeGroup.TeamNumber)
        Catch ex As Exception

        End Try
    End Sub
    Private Sub llblWU_LinkClicked(ByVal sender As Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles llblWU.LinkClicked
        If lblProject.Text.Length > 0 Then Call mnuProjectBrowser_Click(Me, Nothing)
    End Sub
    Private _bAP As Boolean, fAP As frmClientAffinity
    Public Property bAP() As Boolean
        Get
            Return _bAP
        End Get
        Set(ByVal value As Boolean)
            _bAP = value
        End Set
    End Property
    Private Sub mnuPFmanager_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuPFmanager.Click
        Try
            If Not bAP Then
                fAP = New frmClientAffinity
                AddHandler fAP.FormClosed, AddressOf fAP_Close
                _bAP = True
                fAP.Show(Me)
            Else
                fAP.BringToFront()
            End If
        Catch ex As Exception

        End Try
    End Sub
    Private Sub mnuPlist_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuPlist.Click
        Dim fPlist As New frmPBList
        frmPBList.FillView()
        frmPBList.ShowDialog()
    End Sub
    Public Sub fAP_Close()
        _bAP = False
    End Sub
#End Region
#Region "Timers"
    Private Sub tDT_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tDT.Tick
        tsTime.Text = DateTime.Now.ToShortDateString & " " & DateTime.Now.ToLongTimeString
        If mySettings.bExtendGUI And selClient.Index > 0 Then
            If selClient.GuiController.Queue.Progress >= 1 And selClient.GuiController.Running(True) Then
                If selClient.GuiController.Queue.Eta <> DateTime.MinValue And selClient.GuiController.Queue.Eta <> #1/1/2000# Then
                    Dim tsFrame As TimeSpan = _scDT.Subtract(DateTime.Now)
                    Dim strRet As String = ""
                    If tsFrame.Days > 0 Then
                        If tsFrame.Days < 10 Then
                            strRet &= "0" & tsFrame.Days & ":"
                        Else
                            strRet &= tsFrame.Days & ":"
                        End If
                    Else
                        strRet &= "00:"
                    End If
                    If tsFrame.Hours > 0 Then
                        If tsFrame.Hours < 10 Then
                            strRet &= "0" & tsFrame.Hours & ":"
                        Else
                            strRet &= tsFrame.Hours & ":"
                        End If
                    Else
                        strRet &= "00:"
                    End If
                    If tsFrame.Minutes > 0 Then
                        If tsFrame.Minutes < 10 Then
                            strRet &= "0" & tsFrame.Minutes & ":"
                        Else
                            strRet &= tsFrame.Minutes & ":"
                        End If
                    Else
                        strRet &= "00:"
                    End If
                    If tsFrame.Seconds > 0 Then
                        If tsFrame.Seconds < 10 Then
                            strRet &= "0" & tsFrame.Seconds
                        Else
                            strRet &= tsFrame.Seconds
                        End If
                    Else
                        strRet &= "00"
                    End If
                    lblRemaining.Text = strRet
                Else
                    lblRemaining.Text = "Unkown"
                End If
            Else
                lblRemaining.Text = "Unkown"
            End If
        Else
            lblRemaining.Text = "Unkown"
        End If
    End Sub
#End Region
#Region "Dynamic updates"
    Private Shared _Updating As Boolean = False
    Public Sub tLogTimeout_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tLogTimeout.Tick
        Try
            tLogTimeout.Enabled = False
            Dim lFile As String = selClient.GuiController.ClientLocation & "\FAHlog.txt"
            If Not My.Computer.FileSystem.FileExists(lFile) Then Exit Sub
            Dim fStream As FileStream = New FileStream(lFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
            Dim sRead As New StreamReader(fStream)
            If sRead.EndOfStream Then Exit Sub
            Dim rtNew As New RichTextBox
            rtNew.MaxLength = Int32.MaxValue
            rtNew.Text = sRead.ReadToEnd
            rtNew.Text = rtNew.Text.TrimEnd(vbNewLine).TrimEnd(vbCr).TrimEnd(vbCrLf)
            sRead.Close()
            fStream.Close()
            sRead = Nothing
            fStream = Nothing
            'get diffrence
            If rtLOG.TextLength = 0 Then
                'assume empty always load
                rtLOG.Text = rtNew.Text
                GoTo Scroll
            ElseIf Mid(rtNew.Text, 1, rtLOG.TextLength) = Mid(rtLOG.Text, 1, rtLOG.TextLength) Then
                'Same text, with new lines
                rtLOG.Text.Insert(rtLOG.TextLength, Mid(rtNew.TextLength, rtLOG.TextLength))
                GoTo Scroll
            Else
                'Diffrent text, update
                rtLOG.Text = rtNew.Text
                rtNew = Nothing
                GoTo Scroll
            End If
Scroll:
            rtNew = Nothing
            rtLOG.SelectionLength = 0
            rtLOG.SelectionStart = rtLOG.TextLength - 2
            rtLOG.ScrollToCaret()
        Catch ex As Exception

        End Try
    End Sub
    Private _wClient As clsClientConfiguration.clsClientConfigs.sClientSettings.sClient
    Public Sub tQueueTimeout_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tQueueTimeout.Tick
        Try
            tQueueTimeout.Enabled = False
            _Updating = True
            If selClient.PandeGroup.ServiceMode Then
                If selClient.GuiController.ServiceState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eServiceState.Running Then
                    Dim sStatus As String = selClient.GuiController.Queue.ActiveSlot.Status
                    If sStatus <> "1" Then GoTo Clean
                    If Not selClient.GuiController.Queue.HasError Then
                        'pbSig.ImageLocation = "http://folding.extremeoverclocking.com/sigs/sigimage.php?un=" & selClient.PandeGroup.UserName & "&t=" & selClient.PandeGroup.TeamNumber & "&bg=1"
                        lblPFraction.Text = selClient.GuiController.Queue.PerformanceFraction
                        lblStuckUploads.Text = selClient.GuiController.Queue.TotalUploadFailures.ToString
                        llblName.Text = selClient.GuiController.Queue.ActiveSlot.UserName
                        llblTeam.Text = "(" & selClient.GuiController.Queue.ActiveSlot.TeamNumber & ")"
                        llblTeam.Left = llblName.Left + llblName.Width + 5
                        lblIssued.Text = selClient.GuiController.Queue.ActiveSlot.TimeData.BeginTime.ToShortDateString & " " & selClient.GuiController.Queue.ActiveSlot.TimeData.BeginTime.ToShortTimeString
                        lblExpires.Text = selClient.GuiController.Queue.ActiveSlot.Expires.ToShortDateString & " " & selClient.GuiController.Queue.ActiveSlot.Expires.ToShortTimeString
                        Dim sProgress As Int16 = selClient.GuiController.Queue.Progress
                        If sProgress = -2 Then
                            lblProgress.Text = "Ready"
                            tPB.Value = 100
                        ElseIf sProgress = -1 Then
                            lblProgress.Text = "Unknown"
                            tPB.Value = 0
                        Else
                            lblProgress.Text = sProgress.ToString & "%"
                            tPB.Visible = True
                            tPB.Value = sProgress
                            Select Case CDec(selClient.GuiController.Queue.PerformanceFraction) * 100
                                Case Is > Decimal.One * 90
                                    tPB.MarqueeAnimationSpeed = 100
                                Case Is > Decimal.One * 80
                                    tPB.MarqueeAnimationSpeed = 200
                                Case Is > Decimal.One * 70
                                    tPB.MarqueeAnimationSpeed = 300
                                Case Is > Decimal.One * 60
                                    tPB.MarqueeAnimationSpeed = 400
                                Case Is > Decimal.One * 50
                                    tPB.MarqueeAnimationSpeed = 500
                                Case Is > Decimal.One * 40
                                    tPB.MarqueeAnimationSpeed = 600
                                Case Is > Decimal.One * 30
                                    tPB.MarqueeAnimationSpeed = 700
                                Case Is > Decimal.One * 20
                                    tPB.MarqueeAnimationSpeed = 800
                                Case Is > Decimal.One * 10
                                    tPB.MarqueeAnimationSpeed = 900
                                Case Else
                                    tPB.MarqueeAnimationSpeed = 1000
                            End Select
                        End If

                        lblCFrameTime.Text = selClient.GuiController.Queue.tsFrame.ToString
                        If selClient.GuiController.Queue.PPD_LastFrame >= 1 Then
                            lblPPD.Text = selClient.GuiController.Queue.PPD_LastFrame.ToString
                        Else
                            lblPPD.Text = "Unkown"
                        End If
                        _scDT = selClient.GuiController.Queue.Eta
                        If _scDT <> #1/1/2000# And _scDT <> DateTime.MinValue Then
                            lblEta.Text = _scDT.ToShortDateString & " " & _scDT.ToShortTimeString
                        Else
                            lblEta.Text = "Unkown"
                        End If
                        lblProject.Text = selClient.GuiController.Queue.ActiveSlot.Project.Project & " (Run " & selClient.GuiController.Queue.ActiveSlot.Project.Run & " Clone " & selClient.GuiController.Queue.ActiveSlot.Project.Clone & " Generation " & selClient.GuiController.Queue.ActiveSlot.Project.Gen & ")"
                        If ProjectInfo.KnownProject(selClient.GuiController.Queue.ActiveSlot.Project.Project) Then
                            lblPoints.Text = ProjectInfo.Project(selClient.GuiController.Queue.ActiveSlot.Project.Project).Credit
                            lblCore.Text = ProjectInfo.Project(selClient.GuiController.Queue.ActiveSlot.Project.Project).Code
                            lblAtoms.Text = ProjectInfo.Project(selClient.GuiController.Queue.ActiveSlot.Project.Project).NumberOfAtoms
                            'ProjectInfo.Project(selClient.GuiController.Queue.ActiveSlot.Project.Project).FinalDeadline
                            Dim dDue As DateTime = selClient.GuiController.Queue.ActiveSlot.TimeData.BeginTime.AddDays(CInt(Mid(ProjectInfo.Project(selClient.GuiController.Queue.ActiveSlot.Project.Project).PreferredDays, 1, 1)))
                            lblDue.Text = dDue.ToShortDateString & " " & dDue.ToShortTimeString
                            llblWU.Enabled = True
                        Else
                            lblPoints.Text = "Unknown"
                            lblCore.Text = "Unknown"
                            lblAtoms.Text = "Unkown"
                            lblDue.Text = "Unknown"
                            llblWU.Enabled = False
                            If mySettings.bAutoDownProjects Then
                                If (Not mySettings.LastProjectUpdate = selClient.GuiController.Queue.ActiveSlot.Project.Project) Xor (DateTime.Now.Subtract(mySettings.dtLastProjectUpdate).TotalHours > 3) Then
                                    mySettings.LastProjectUpdate = selClient.GuiController.Queue.ActiveSlot.Project.Project
                                    ProjectInfo.GetProjects()
                                    If ProjectInfo.KnownProject(selClient.GuiController.Queue.ActiveSlot.Project.Project) Then mySettings.LastProjectUpdate = ""
                                End If
                            End If
                        End If
                        If selClient.GuiController.EOCStats.Filled And Not selClient.GuiController.EOCStats.LastUpdate.IsEmpty Then
                            With selClient.GuiController.EOCStats
                                lblEocUpdate.Text = .LastUpdate.UpdateStatus.LastUpdateString
                                lblPointsUpdate.Text = .LastUpdate.User.Points_Update
                                lblPointsToday.Text = .LastUpdate.User.Points_Today
                                lbl24HAverage.Text = .LastUpdate.User.Points_24h_Avg
                                lblProcessedWU.Text = .WU_Update
                            End With
                        Else
                            lblEocUpdate.Text = ""
                            lblPointsUpdate.Text = ""
                            lblPointsToday.Text = ""
                            lbl24HAverage.Text = ""
                            lblProcessedWU.Text = ""
                        End If
                        If selClient.GuiController.Statistics.ActivePRGC.KnownFrames <= 2 Then
                            If selClient.GuiController.Statistics.ActivePRGC.bHasReferenceValues Then
                                lbl3Frames.Text = selClient.GuiController.Statistics.ActivePRGC.rv3Frames_string
                                lblAllFrames.Text = selClient.GuiController.Statistics.ActivePRGC.rvAllFrames_String
                            Else
                                lbl3Frames.Text = lblCFrameTime.Text & "*"
                                lblAllFrames.Text = lblCFrameTime.Text & "*"
                            End If
                        Else
                            lbl3Frames.Text = selClient.GuiController.Statistics.ActivePRGC.strAvgFrametime(3)
                            lblAllFrames.Text = selClient.GuiController.Statistics.ActivePRGC.strAvgFrametime(100)
                        End If
                        _Updating = False
                    Else
                        GoTo Clean
                    End If
                End If
            Else
                If selClient.GuiController.Running(True) Then
                    Dim sStatus As String = selClient.GuiController.Queue.ActiveSlot.Status
                    If sStatus <> "1" Then GoTo Clean
                    If Not selClient.GuiController.Queue.HasError Then
                        'pbSig.ImageLocation = "http://folding.extremeoverclocking.com/sigs/sigimage.php?un=" & selClient.PandeGroup.UserName & "&t=" & selClient.PandeGroup.TeamNumber & "&bg=1"
                        lblPFraction.Text = selClient.GuiController.Queue.PerformanceFraction
                        lblStuckUploads.Text = selClient.GuiController.Queue.TotalUploadFailures.ToString
                        lblWUReady.Text = selClient.GuiController.Queue.WUs_Ready.ToString
                        llblName.Text = selClient.GuiController.Queue.ActiveSlot.UserName
                        llblTeam.Text = "(" & selClient.GuiController.Queue.ActiveSlot.TeamNumber & ")"
                        llblTeam.Left = llblName.Left + llblName.Width + 5
                        lblIssued.Text = selClient.GuiController.Queue.ActiveSlot.TimeData.BeginTime.ToShortDateString & " " & selClient.GuiController.Queue.ActiveSlot.TimeData.BeginTime.ToShortTimeString
                        lblExpires.Text = selClient.GuiController.Queue.ActiveSlot.Expires.ToShortDateString & " " & selClient.GuiController.Queue.ActiveSlot.Expires.ToShortTimeString
                        Dim sProgress As Int16 = selClient.GuiController.Queue.Progress
                        If sProgress = -2 Then
                            lblProgress.Text = "Ready"
                            tPB.Value = 100
                        ElseIf sProgress = -1 Then
                            lblProgress.Text = "Unknown"
                            tPB.Value = 0
                        Else
                            lblProgress.Text = sProgress.ToString & "%"
                            tPB.Visible = True
                            tPB.Value = sProgress
                            Select Case CDec(selClient.GuiController.Queue.PerformanceFraction) * 100
                                Case Is > Decimal.One * 90
                                    tPB.MarqueeAnimationSpeed = 100
                                Case Is > Decimal.One * 80
                                    tPB.MarqueeAnimationSpeed = 200
                                Case Is > Decimal.One * 70
                                    tPB.MarqueeAnimationSpeed = 300
                                Case Is > Decimal.One * 60
                                    tPB.MarqueeAnimationSpeed = 400
                                Case Is > Decimal.One * 50
                                    tPB.MarqueeAnimationSpeed = 500
                                Case Is > Decimal.One * 40
                                    tPB.MarqueeAnimationSpeed = 600
                                Case Is > Decimal.One * 30
                                    tPB.MarqueeAnimationSpeed = 700
                                Case Is > Decimal.One * 20
                                    tPB.MarqueeAnimationSpeed = 800
                                Case Is > Decimal.One * 10
                                    tPB.MarqueeAnimationSpeed = 900
                                Case Else
                                    tPB.MarqueeAnimationSpeed = 1000
                            End Select
                        End If
                        lblCFrameTime.Text = selClient.GuiController.Queue.tsFrame.ToString
                        If selClient.GuiController.Queue.PPD_LastFrame >= 1 Then
                            lblPPD.Text = selClient.GuiController.Queue.PPD_LastFrame.ToString
                        Else
                            lblPPD.Text = "Unkown"
                        End If
                        _scDT = selClient.GuiController.Queue.Eta
                        If _scDT <> #1/1/2000# And _scDT <> DateTime.MinValue Then
                            lblEta.Text = _scDT.ToShortDateString & " " & _scDT.ToShortTimeString
                        Else
                            lblEta.Text = "Unkown"
                        End If
                        lblProject.Text = selClient.GuiController.Queue.ActiveSlot.Project.Project & " (Run " & selClient.GuiController.Queue.ActiveSlot.Project.Run & " Clone " & selClient.GuiController.Queue.ActiveSlot.Project.Clone & " Generation " & selClient.GuiController.Queue.ActiveSlot.Project.Gen & ")"
                        If ProjectInfo.KnownProject(selClient.GuiController.Queue.ActiveSlot.Project.Project) Then
                            lblPoints.Text = ProjectInfo.Project(selClient.GuiController.Queue.ActiveSlot.Project.Project).Credit
                            lblCore.Text = ProjectInfo.Project(selClient.GuiController.Queue.ActiveSlot.Project.Project).Code
                            lblAtoms.Text = ProjectInfo.Project(selClient.GuiController.Queue.ActiveSlot.Project.Project).NumberOfAtoms
                            'ProjectInfo.Project(selClient.GuiController.Queue.ActiveSlot.Project.Project).FinalDeadline
                            Dim dDue As DateTime = selClient.GuiController.Queue.ActiveSlot.TimeData.BeginTime.AddDays(CInt(Mid(ProjectInfo.Project(selClient.GuiController.Queue.ActiveSlot.Project.Project).PreferredDays, 1, 1)))
                            lblDue.Text = dDue.ToShortDateString & " " & dDue.ToShortTimeString
                            llblWU.Enabled = True
                        Else
                            lblPoints.Text = "Unknown"
                            lblCore.Text = "Unknown"
                            lblAtoms.Text = "Unkown"
                            lblDue.Text = "Unknown"
                            llblWU.Enabled = False
                            If mySettings.bAutoDownProjects Then
                                If (Not mySettings.LastProjectUpdate = selClient.GuiController.Queue.ActiveSlot.Project.Project) Xor (DateTime.Now.Subtract(mySettings.dtLastProjectUpdate).TotalHours > 3) Then
                                    mySettings.LastProjectUpdate = selClient.GuiController.Queue.ActiveSlot.Project.Project
                                    ProjectInfo.GetProjects()
                                    If ProjectInfo.KnownProject(selClient.GuiController.Queue.ActiveSlot.Project.Project) Then mySettings.LastProjectUpdate = ""
                                End If
                            End If
                        End If
                        If selClient.GuiController.EOCStats.Filled And Not selClient.GuiController.EOCStats.LastUpdate.IsEmpty Then
                            With selClient.GuiController.EOCStats
                                lblEocUpdate.Text = .LastUpdate.UpdateStatus.LastUpdateString
                                If selClient.GuiController.EOCStats.ShouldRefresh Then lblEocUpdate.Text &= "*"
                                lblPointsUpdate.Text = .LastUpdate.User.Points_Update
                                lblPointsToday.Text = .LastUpdate.User.Points_Today
                                lbl24HAverage.Text = .LastUpdate.User.Points_24h_Avg
                                lblProcessedWU.Text = .WU_Update
                            End With
                        Else
                            lblEocUpdate.Text = ""
                            lblPointsUpdate.Text = ""
                            lblPointsToday.Text = ""
                            lbl24HAverage.Text = ""
                            lblProcessedWU.Text = ""
                        End If
                        If selClient.GuiController.Statistics.ActivePRGC.KnownFrames <= 2 Then
                            If selClient.GuiController.Statistics.ActivePRGC.bHasReferenceValues Then
                                lbl3Frames.Text = selClient.GuiController.Statistics.ActivePRGC.rv3Frames_string
                                lblAllFrames.Text = selClient.GuiController.Statistics.ActivePRGC.rvAllFrames_String
                            Else
                                lbl3Frames.Text = lblCFrameTime.Text & "*"
                                lblAllFrames.Text = lblCFrameTime.Text & "*"
                            End If
                        Else
                            lbl3Frames.Text = selClient.GuiController.Statistics.ActivePRGC.strAvgFrametime(3)
                            lblAllFrames.Text = selClient.GuiController.Statistics.ActivePRGC.strAvgFrametime(100)
                        End If
                        _Updating = False
                    Else
                        GoTo Clean
                    End If
                Else
                    GoTo Clean
                End If
            End If
            'tPB.Width = Me.ClientSize.Width - tsTime.Width - tsTotalPPD.Width - 100
            Exit Sub
Clean:
            _Updating = True
            llblWU.Enabled = False
            If selClient.GuiController.EOCStats.Filled And Not selClient.GuiController.EOCStats.LastUpdate.IsEmpty Then
                With selClient.GuiController.EOCStats
                    lblEocUpdate.Text = .LastUpdate.UpdateStatus.LastUpdateString
                    If selClient.GuiController.EOCStats.ShouldRefresh Then lblEocUpdate.Text &= "*"
                    lblPointsUpdate.Text = .LastUpdate.User.Points_Update
                    lblPointsToday.Text = .LastUpdate.User.Points_Today
                    lbl24HAverage.Text = .LastUpdate.User.Points_24h_Avg
                    lblProcessedWU.Text = .WU_Update
                End With
            Else
                lblEocUpdate.Text = ""
                lblPointsUpdate.Text = ""
                lblPointsToday.Text = ""
                lbl24HAverage.Text = ""
                lblProcessedWU.Text = ""
            End If
            lblWUReady.Text = selClient.GuiController.Queue.WUs_Ready.ToString
            lblStuckUploads.Text = selClient.GuiController.Queue.TotalUploadFailures.ToString
            lblPFraction.Text = selClient.GuiController.Queue.PerformanceFraction
            tPB.Value = 0 : lblAllFrames.Text = "" : lbl3Frames.Text = ""
            lblEta.Text = "" : lblAtoms.Text = "" : lblCFrameTime.Text = "" : lblCore.Text = "" : lblDue.Text = "" : lblExpires.Text = "" : lblExpires.Text = "" : lblIssued.Text = "" : lblPoints.Text = "" : lblPPD.Text = "" : lblProgress.Text = "" : lblProject.Text = "" : lblRemaining.Text = ""
            llblName.Text = "" : llblTeam.Text = ""
            'tPB.Width = Me.ClientSize.Width - tsTime.Width - tsTotalPPD.Width - 100
            _Updating = False
        Catch ex As NullReferenceException
            LogWindow.WriteLog("Trying to update the listview before the clients are fully loaded.")
        Catch ex As Exception
            If selClient.GuiController.Queue.HasError Then GoTo Clean
        End Try
    End Sub
    Private Sub tUpdateClient(ByVal Sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
        Try
            'Stopt the timer?
            Dim Client As clsClientConfiguration.clsClientConfigs.sClientSettings.sClient
            Dim bHas As Boolean = False
            Try
                Dim tTimer As System.Timers.Timer = CType(Sender, Timers.Timer)
                For xInd As Int16 = 1 To Clients.GetUpperBound(0)
                    If ReferenceEquals(tUpdates(xInd), tTimer) Then
                        tTimer.Enabled = False
                        Client = Clients(xInd)
                        bHas = True
                        Exit For
                    End If
                Next
            Catch ex As Exception
                LogWindow.WriteError("frmTray, tUpdateClient, ReferenceEquals project", Err, ex.Message)
                Exit Sub
            End Try
            If Not bHas Then
                LogWindow.WriteLog("frmTray, tUpdateClient, ReferenceEquals project - could not find")
                Exit Sub
            End If
            Try 'Update wu info / logfile
                If selClient.Index = Client.Index Then
                    ReadQueue()
                    ReadLOG()
                End If
            Catch ex As Exception
                LogWindow.WriteError("frmTray, tUpdateClient, Determine index", Err, ex.Message)
            End Try

            Dim threadUpdate As New Threading.Thread(AddressOf ThreadedLVCUpdate)
            threadUpdate.Start(Client)

            'tPB.Width = Me.ClientSize.Width - tsTime.Width - tsTotalPPD.Width - 100
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
    Public Sub ThreadedLVCUpdate(ByVal Client As clsClientConfiguration.clsClientConfigs.sClientSettings.sClient)
        Try
            If fTray.lvC.InvokeRequired Then
                Dim uSafe As New Ulvc(AddressOf UpdateLvc)
                Me.Invoke(uSafe, New Object() {Client})
            Else
                With fTray.lvC.Items(Client.Index - 1)
                    If Client.PandeGroup.ServiceMode Then
                        If Client.GuiController.ServiceState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eServiceState.Running Then
                            .ImageKey = "GREEN"
                            If Not Client.GuiController.Queue.HasError Then
                                If Client.GuiController.Queue.ActiveSlot.Status = "1" Then    'running
                                    .SubItems(1).Text = Client.GuiController.Queue.ActiveSlot.Project.Project & "(R" & Client.GuiController.Queue.ActiveSlot.Project.Run & ", C" & Client.GuiController.Queue.ActiveSlot.Project.Gen & ", G" & Client.GuiController.Queue.ActiveSlot.Project.Gen & ")"
                                    .SubItems(2).Text = Client.GuiController.Queue.CoreVersion
                                    If Client.GuiController.Queue.Progress >= 0 Then
                                        .SubItems(3).Text = Client.GuiController.Queue.Progress
                                    Else
                                        .SubItems(3).Text = ""
                                    End If

                                    Dim strPPD As String = Client.GuiController.Queue.PPD_LastFrame.ToString
                                    If Not strPPD = "0" Then
                                        If InStr(strPPD, ",") <> 0 Then
                                            Dim iDigits As Int16 = strPPD.Length - strPPD.LastIndexOf(",")
                                            For iAddDigits As Int16 = 4 To iDigits Step -1
                                                strPPD &= "0"
                                            Next
                                        Else
                                            strPPD &= ",0000"
                                        End If
                                        .SubItems(4).Text = strPPD
                                    Else
                                        'Look for statistical data 
                                        If Not Client.GuiController.Statistics.ActivePRGC.KnownFrames = 0 Then
                                            'Use last frametime
                                            If ProjectInfo.KnownProject(Client.GuiController.Queue.ActiveSlot.Project.Project) Then
                                                strPPD = ProjectInfo.PPD(Client.GuiController.Queue.ActiveSlot.Project.Project, Client.GuiController.Statistics.ActivePRGC.AverageFrameTime).ToString
                                                If InStr(strPPD, ",") <> 0 Then
                                                    Dim iDigits As Int16 = strPPD.Length - strPPD.LastIndexOf(",")
                                                    For iAddDigits As Int16 = 4 To iDigits Step -1
                                                        strPPD &= "0"
                                                    Next
                                                Else
                                                    strPPD &= ",0000"
                                                End If
                                                .SubItems(4).Text = strPPD
                                            Else
                                                .SubItems(4).Text = strPPD
                                            End If
                                        Else
                                            'Look for reference values
                                            If Client.GuiController.Statistics.ActivePRGC.bHasReferenceValues Then
                                                'Use reference frame time
                                                strPPD = ProjectInfo.PPD(Client.GuiController.Queue.ActiveSlot.Project.Project, Client.GuiController.Statistics.ActivePRGC.rv3Frames).ToString
                                                If InStr(strPPD, ",") <> 0 Then
                                                    Dim iDigits As Int16 = strPPD.Length - strPPD.LastIndexOf(",")
                                                    For iAddDigits As Int16 = 4 To iDigits Step -1
                                                        strPPD &= "0"
                                                    Next
                                                Else
                                                    strPPD &= ",0000"
                                                End If
                                                .SubItems(4).Text = strPPD
                                            Else
                                                'Zero
                                                .SubItems(4).Text = strPPD
                                            End If
                                        End If
                                    End If
                                    If Client.GuiController.Queue.PPD_Effective <> -1 Then
                                        strPPD = Client.GuiController.Queue.PPD_Effective.ToString
                                        If InStr(strPPD, ",") <> 0 Then
                                            Dim iDigits As Int16 = strPPD.Length - strPPD.LastIndexOf(",")
                                            For iAddDigits As Int16 = 4 To iDigits Step -1
                                                strPPD &= "0"
                                            Next
                                        Else
                                            strPPD &= ",0000"
                                        End If
                                        .SubItems(5).Text = strPPD
                                    Else
                                        .SubItems(5).Text = "0,0000"
                                    End If
                                    .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                    .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                    .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                                ElseIf Client.GuiController.Queue.ActiveSlot.Status = "2" Then 'Ready
                                    .SubItems(3).Text = "Ready"
                                    For yInd As Int16 = 4 To 5
                                        .SubItems(yInd).Text = ""
                                    Next
                                    .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                    .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                    .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                                ElseIf Client.GuiController.Queue.ActiveSlot.Status = "3" Then 'Downloading
                                    .SubItems(2).Text = "Downloading"
                                    For yInd As Int16 = 3 To 5
                                        .SubItems(yInd).Text = ""
                                    Next
                                    .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                    .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                    .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                                ElseIf Client.GuiController.Queue.ActiveSlot.Status = "0" Then 'Iddle
                                    .SubItems(1).Text = "Idle"
                                    For yInd As Int16 = 2 To 6
                                        .SubItems(yInd).Text = ""
                                    Next
                                    .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                    .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                    .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                                    .ImageKey = "YELLOW"
                                End If
                                If Not Client.PandeGroup.ServiceMode Then
                                    Client.GuiController.IsService = False
                                    If Client.GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Err Then
                                        .SubItems(9).Text = "Err"
                                    ElseIf Client.GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Hidden Then
                                        .SubItems(9).Text = "-hidden-"
                                    ElseIf Client.GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Visible Then
                                        .SubItems(9).Text = "-visible-"
                                    Else
                                        MsgBox(Client.GuiController.wState)
                                    End If
                                Else
                                    Client.GuiController.IsService = True
                                    Client.GuiController.AttachToSC()
                                    Client.GuiController.StartWatching()
                                    .SubItems(9).Text = ("-service-")
                                End If
                            Else
                                .ImageKey = "Red"    'edit for displaying error
                                .SubItems(1).Text = "Error"
                                For xInd As Int16 = 1 To 5
                                    .SubItems(xInd).Text = ""
                                Next
                                .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                            End If
                        ElseIf Client.GuiController.ServiceState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eServiceState.Paused Then
                            .ImageKey = "YELLOW"
                            If Not Client.GuiController.Queue.HasError Then
                                If Client.GuiController.Queue.ActiveSlot.Status = "1" Then    'running
                                    .SubItems(1).Text = Client.GuiController.Queue.ActiveSlot.Project.Project & "(R" & Client.GuiController.Queue.ActiveSlot.Project.Run & ", C" & Client.GuiController.Queue.ActiveSlot.Project.Gen & ", G" & Client.GuiController.Queue.ActiveSlot.Project.Gen & ")"
                                    .SubItems(2).Text = Client.GuiController.Queue.CoreVersion
                                    If Client.GuiController.Queue.Progress >= 0 Then
                                        .SubItems(3).Text = Client.GuiController.Queue.Progress
                                    Else
                                        .SubItems(3).Text = ""
                                    End If
                                    .SubItems(4).Text = "- Paused -"
                                ElseIf Client.GuiController.Queue.ActiveSlot.Status = "2" Then 'Ready
                                    .SubItems(2).Text = "Ready"
                                    For yInd As Int16 = 3 To 5
                                        .SubItems(yInd).Text = ""
                                    Next
                                    .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                    .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                    .SubItems(8).Text = Client.GuiController.Queue.TotalUploadFailures.ToString
                                ElseIf Client.GuiController.Queue.ActiveSlot.Status = "3" Then 'Downloading
                                    .SubItems(1).Text = "Downloading"
                                    For yInd As Int16 = 3 To 5
                                        .SubItems(yInd).Text = ""
                                    Next
                                    .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                    .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                    .SubItems(8).Text = Client.GuiController.Queue.TotalUploadFailures.ToString
                                ElseIf Client.GuiController.Queue.ActiveSlot.Status = "0" Then 'Iddle
                                    .ImageKey = "Yellow"
                                    .SubItems(1).Text = "Idle"
                                    For yInd As Int16 = 2 To 5
                                        .SubItems(yInd).Text = ""
                                    Next
                                    .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                    .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                    .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                                End If
                                If Not Client.PandeGroup.ServiceMode Then
                                    Client.GuiController.IsService = False
                                    If Client.GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Err Then
                                        .SubItems(9).Text = "Err"
                                    ElseIf Client.GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Hidden Then
                                        .SubItems(9).Text = "-hidden-"
                                    ElseIf Client.GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Visible Then
                                        .SubItems(9).Text = "-visible-"
                                    Else
                                        MsgBox(Client.GuiController.wState)
                                    End If
                                Else
                                    Client.GuiController.IsService = True
                                    Client.GuiController.AttachToSC()
                                    Client.GuiController.StartWatching()
                                    .SubItems(9).Text = ("-service-")
                                End If
                            Else
                                .ImageKey = "YELLOW"    'edit for displaying error
                                'Add an error icon to the tray
                                .SubItems(1).Text = "Error"
                                For xInd As Int16 = 2 To 5
                                    .SubItems(xInd).Text = ""
                                Next
                                .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                            End If
                        ElseIf Client.GuiController.ServiceState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eServiceState.Stopped Then
                            .ImageKey = "RED"
                            For xInd As Int16 = 1 To 5
                                .SubItems(xInd).Text = ""
                            Next
                            .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                            .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                            .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                        End If
                    Else
                        If Client.GuiController.Running(True) Then
                            .ImageKey = "Green"
                            If Not Client.GuiController.Queue.HasError Then
                                If Client.GuiController.Queue.ActiveSlot.Status = "1" Then    'running
                                    .SubItems(1).Text = Client.GuiController.Queue.ActiveSlot.Project.Project & "(R" & Client.GuiController.Queue.ActiveSlot.Project.Run & ", C" & Client.GuiController.Queue.ActiveSlot.Project.Gen & ", G" & Client.GuiController.Queue.ActiveSlot.Project.Gen & ")"
                                    .SubItems(2).Text = Client.GuiController.Queue.CoreVersion
                                    If Client.GuiController.Queue.Progress >= 0 Then
                                        .SubItems(3).Text = Client.GuiController.Queue.Progress
                                    Else
                                        .SubItems(3).Text = " - "
                                    End If
                                    Dim strPPD As String = Client.GuiController.Queue.PPD_LastFrame.ToString
                                    If Not strPPD = "0" Then
                                        If InStr(strPPD, ",") <> 0 Then
                                            Dim iDigits As Int16 = strPPD.Length - strPPD.LastIndexOf(",")
                                            For iAddDigits As Int16 = 4 To iDigits Step -1
                                                strPPD &= "0"
                                            Next
                                        Else
                                            strPPD &= ",0000"
                                        End If
                                        .SubItems(4).Text = strPPD
                                    Else
                                        'Look for statistical data 
                                        If Not Client.GuiController.Statistics.ActivePRGC.KnownFrames = 0 Then
                                            'Use last frametime
                                            If ProjectInfo.KnownProject(Client.GuiController.Queue.ActiveSlot.Project.Project) Then
                                                strPPD = ProjectInfo.PPD(Client.GuiController.Queue.ActiveSlot.Project.Project, Client.GuiController.Statistics.ActivePRGC.AverageFrameTime).ToString
                                                If InStr(strPPD, ",") <> 0 Then
                                                    Dim iDigits As Int16 = strPPD.Length - strPPD.LastIndexOf(",")
                                                    For iAddDigits As Int16 = 4 To iDigits Step -1
                                                        strPPD &= "0"
                                                    Next
                                                Else
                                                    strPPD &= ",0000"
                                                End If
                                                .SubItems(4).Text = strPPD
                                            Else
                                                .SubItems(4).Text = strPPD
                                            End If
                                        Else
                                            'Look for reference values
                                            If Client.GuiController.Statistics.ActivePRGC.bHasReferenceValues Then
                                                'Use reference frame time
                                                strPPD = ProjectInfo.PPD(Client.GuiController.Queue.ActiveSlot.Project.Project, Client.GuiController.Statistics.ActivePRGC.rv3Frames).ToString
                                                If InStr(strPPD, ",") <> 0 Then
                                                    Dim iDigits As Int16 = strPPD.Length - strPPD.LastIndexOf(",")
                                                    For iAddDigits As Int16 = 4 To iDigits Step -1
                                                        strPPD &= "0"
                                                    Next
                                                Else
                                                    strPPD &= ",0000"
                                                End If
                                                .SubItems(4).Text = strPPD
                                            Else
                                                'Zero
                                                .SubItems(4).Text = strPPD
                                            End If
                                        End If
                                    End If
                                    If Client.GuiController.Queue.PPD_Effective <> -1 Then
                                        strPPD = Client.GuiController.Queue.PPD_Effective.ToString
                                        If InStr(strPPD, ",") <> 0 Then
                                            Dim iDigits As Int16 = strPPD.Length - strPPD.LastIndexOf(",")
                                            For iAddDigits As Int16 = 4 To iDigits Step -1
                                                strPPD &= "0"
                                            Next
                                        Else
                                            strPPD &= ",0000"
                                        End If
                                        .SubItems(5).Text = strPPD
                                    Else
                                        .SubItems(5).Text = "0,0000"
                                    End If
                                    .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                    .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                    .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                                ElseIf Client.GuiController.Queue.ActiveSlot.Status = "2" Then 'Ready
                                    .SubItems(1).Text = ""
                                    .SubItems(2).Text = ""
                                    .SubItems(3).Text = "Ready"
                                    For yInd As Int16 = 4 To 5
                                        .SubItems(yInd).Text = ""
                                    Next
                                    .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                    .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                    .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                                ElseIf Client.GuiController.Queue.ActiveSlot.Status = "3" Then 'Downloading
                                    .SubItems(1).Text = "Downloading"
                                    For yInd As Int16 = 2 To 5
                                        .SubItems(yInd).Text = ""
                                    Next
                                    .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                    .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                    .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                                ElseIf Client.GuiController.Queue.ActiveSlot.Status = "0" Then 'Iddle
                                    .ImageKey = "Yellow"
                                    .SubItems(1).Text = "Idle"
                                    For yInd As Int16 = 2 To 5
                                        .SubItems(yInd).Text = ""
                                    Next
                                    .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                    .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                    .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                                End If
                                If Not Client.PandeGroup.ServiceMode Then
                                    Client.GuiController.IsService = False
                                    If Client.GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Err Then
                                        .SubItems(9).Text = "Err"
                                    ElseIf Client.GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Hidden Then
                                        .SubItems(9).Text = "-hidden-"
                                    ElseIf Client.GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Visible Then
                                        .SubItems(9).Text = "-visible-"
                                    Else
                                        MsgBox(Client.GuiController.wState)
                                    End If
                                Else
                                    Client.GuiController.IsService = True
                                    Client.GuiController.AttachToSC()
                                    Client.GuiController.StartWatching()
                                    .SubItems(9).Text = ("-service-")
                                End If
                            End If
                        Else
                            .ImageKey = "Red"
                            For xInd As Int16 = 1 To 5
                                .SubItems(xInd).Text = ""
                            Next
                            .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                            .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                            .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                            .SubItems(9).Text = ""
                        End If
                    End If
                End With
                Dim iTPPD As Double = 0, iEPPD As Double = 0
                Try
                    For xInd As Int16 = 0 To fTray.lvC.Items.Count - 1
                        If fTray.lvC.Items(xInd).SubItems(4).Text <> "" Then iTPPD += CDbl(fTray.lvC.Items(xInd).SubItems(4).Text)
                        If fTray.lvC.Items(xInd).SubItems(5).Text <> "" Then iEPPD += CDbl(fTray.lvC.Items(xInd).SubItems(5).Text)
                    Next
                    Math.Round(iTPPD, 4)
                    Math.Round(iEPPD, 4)
                    fTray.tsTotalPPD.Text = iTPPD.ToString & " (" & iEPPD.ToString & ")"
                Catch ex As Exception
                End Try
            End If
        Catch ex As Exception
            LogWindow.WriteError("frmTray, threaded lvc update", Err)
        End Try
    End Sub
    Public Delegate Sub Ulvc(ByVal Client)
    Public Sub UpdateLvc(ByVal Client)
        Try
            With fTray.lvC.Items(Client.Index - 1)
                If Client.PandeGroup.ServiceMode Then
                    If Client.GuiController.ServiceState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eServiceState.Running Then
                        .ImageKey = "GREEN"
                        If Not Client.GuiController.Queue.HasError Then
                            If Client.GuiController.Queue.ActiveSlot.Status = "1" Then    'running
                                .SubItems(1).Text = Client.GuiController.Queue.ActiveSlot.Project.Project & "(R" & Client.GuiController.Queue.ActiveSlot.Project.Run & ", C" & Client.GuiController.Queue.ActiveSlot.Project.Gen & ", G" & Client.GuiController.Queue.ActiveSlot.Project.Gen & ")"
                                .SubItems(2).Text = Client.GuiController.Queue.CoreVersion
                                If Client.GuiController.Queue.Progress >= 0 Then
                                    .SubItems(3).Text = Client.GuiController.Queue.Progress
                                Else
                                    .SubItems(3).Text = ""
                                End If

                                Dim strPPD As String = Client.GuiController.Queue.PPD_LastFrame.ToString
                                If Not strPPD = "0" Then
                                    If InStr(strPPD, ",") <> 0 Then
                                        Dim iDigits As Int16 = strPPD.Length - strPPD.LastIndexOf(",")
                                        For iAddDigits As Int16 = 4 To iDigits Step -1
                                            strPPD &= "0"
                                        Next
                                    Else
                                        strPPD &= ",0000"
                                    End If
                                    .SubItems(4).Text = strPPD
                                Else
                                    'Look for statistical data 
                                    If Not Client.GuiController.Statistics.ActivePRGC.KnownFrames = 0 Then
                                        'Use last frametime
                                        If ProjectInfo.KnownProject(Client.GuiController.Queue.ActiveSlot.Project.Project) Then
                                            strPPD = ProjectInfo.PPD(Client.GuiController.Queue.ActiveSlot.Project.Project, Client.GuiController.Statistics.ActivePRGC.AverageFrameTime).ToString
                                            If InStr(strPPD, ",") <> 0 Then
                                                Dim iDigits As Int16 = strPPD.Length - strPPD.LastIndexOf(",")
                                                For iAddDigits As Int16 = 4 To iDigits Step -1
                                                    strPPD &= "0"
                                                Next
                                            Else
                                                strPPD &= ",0000"
                                            End If
                                            .SubItems(4).Text = strPPD
                                        Else
                                            .SubItems(4).Text = strPPD
                                        End If
                                    Else
                                        'Look for reference values
                                        If Client.GuiController.Statistics.ActivePRGC.bHasReferenceValues Then
                                            'Use reference frame time
                                            strPPD = ProjectInfo.PPD(Client.GuiController.Queue.ActiveSlot.Project.Project, Client.GuiController.Statistics.ActivePRGC.rv3Frames).ToString
                                            If InStr(strPPD, ",") <> 0 Then
                                                Dim iDigits As Int16 = strPPD.Length - strPPD.LastIndexOf(",")
                                                For iAddDigits As Int16 = 4 To iDigits Step -1
                                                    strPPD &= "0"
                                                Next
                                            Else
                                                strPPD &= ",0000"
                                            End If
                                            .SubItems(4).Text = strPPD
                                        Else
                                            'Zero
                                            .SubItems(4).Text = strPPD
                                        End If
                                    End If
                                End If
                                If Client.GuiController.Queue.PPD_Effective <> -1 Then
                                    strPPD = Client.GuiController.Queue.PPD_Effective.ToString
                                    If InStr(strPPD, ",") <> 0 Then
                                        Dim iDigits As Int16 = strPPD.Length - strPPD.LastIndexOf(",")
                                        For iAddDigits As Int16 = 4 To iDigits Step -1
                                            strPPD &= "0"
                                        Next
                                    Else
                                        strPPD &= ",0000"
                                    End If
                                    .SubItems(5).Text = strPPD
                                Else
                                    .SubItems(5).Text = "0,0000"
                                End If
                                .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                            ElseIf Client.GuiController.Queue.ActiveSlot.Status = "2" Then 'Ready
                                .SubItems(3).Text = "Ready"
                                For yInd As Int16 = 4 To 5
                                    .SubItems(yInd).Text = ""
                                Next
                                .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                            ElseIf Client.GuiController.Queue.ActiveSlot.Status = "3" Then 'Downloading
                                .SubItems(2).Text = "Downloading"
                                For yInd As Int16 = 3 To 5
                                    .SubItems(yInd).Text = ""
                                Next
                                .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                            ElseIf Client.GuiController.Queue.ActiveSlot.Status = "0" Then 'Iddle
                                .SubItems(1).Text = "Idle"
                                For yInd As Int16 = 2 To 6
                                    .SubItems(yInd).Text = ""
                                Next
                                .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                                .ImageKey = "YELLOW"
                            End If
                            If Not Client.PandeGroup.ServiceMode Then
                                Client.GuiController.IsService = False
                                If Client.GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Err Then
                                    .SubItems(9).Text = "Err"
                                ElseIf Client.GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Hidden Then
                                    .SubItems(9).Text = "-hidden-"
                                ElseIf Client.GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Visible Then
                                    .SubItems(9).Text = "-visible-"
                                Else
                                    MsgBox(Client.GuiController.wState)
                                End If
                            Else
                                Client.GuiController.IsService = True
                                Client.GuiController.AttachToSC()
                                Client.GuiController.StartWatching()
                                .SubItems(9).Text = ("-service-")
                            End If
                        Else
                            .ImageKey = "Red"    'edit for displaying error
                            .SubItems(1).Text = "Error"
                            For xInd As Int16 = 1 To 5
                                .SubItems(xInd).Text = ""
                            Next
                            .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                            .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                            .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                        End If
                    ElseIf Client.GuiController.ServiceState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eServiceState.Paused Then
                        .ImageKey = "YELLOW"
                        If Not Client.GuiController.Queue.HasError Then
                            If Client.GuiController.Queue.ActiveSlot.Status = "1" Then    'running
                                .SubItems(1).Text = Client.GuiController.Queue.ActiveSlot.Project.Project & "(R" & Client.GuiController.Queue.ActiveSlot.Project.Run & ", C" & Client.GuiController.Queue.ActiveSlot.Project.Gen & ", G" & Client.GuiController.Queue.ActiveSlot.Project.Gen & ")"
                                .SubItems(2).Text = Client.GuiController.Queue.CoreVersion
                                If Client.GuiController.Queue.Progress >= 0 Then
                                    .SubItems(3).Text = Client.GuiController.Queue.Progress
                                Else
                                    .SubItems(3).Text = ""
                                End If
                                .SubItems(4).Text = "- Paused -"
                            ElseIf Client.GuiController.Queue.ActiveSlot.Status = "2" Then 'Ready
                                .SubItems(2).Text = "Ready"
                                For yInd As Int16 = 3 To 5
                                    .SubItems(yInd).Text = ""
                                Next
                                .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                .SubItems(8).Text = Client.GuiController.Queue.TotalUploadFailures.ToString
                            ElseIf Client.GuiController.Queue.ActiveSlot.Status = "3" Then 'Downloading
                                .SubItems(1).Text = "Downloading"
                                For yInd As Int16 = 3 To 5
                                    .SubItems(yInd).Text = ""
                                Next
                                .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                .SubItems(8).Text = Client.GuiController.Queue.TotalUploadFailures.ToString
                            ElseIf Client.GuiController.Queue.ActiveSlot.Status = "0" Then 'Iddle
                                .ImageKey = "Yellow"
                                .SubItems(1).Text = "Idle"
                                For yInd As Int16 = 2 To 5
                                    .SubItems(yInd).Text = ""
                                Next
                                .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                            End If
                            If Not Client.PandeGroup.ServiceMode Then
                                Client.GuiController.IsService = False
                                If Client.GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Err Then
                                    .SubItems(9).Text = "Err"
                                ElseIf Client.GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Hidden Then
                                    .SubItems(9).Text = "-hidden-"
                                ElseIf Client.GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Visible Then
                                    .SubItems(9).Text = "-visible-"
                                Else
                                    MsgBox(Client.GuiController.wState)
                                End If
                            Else
                                Client.GuiController.IsService = True
                                Client.GuiController.AttachToSC()
                                Client.GuiController.StartWatching()
                                .SubItems(9).Text = ("-service-")
                            End If
                        Else
                            .ImageKey = "YELLOW"    'edit for displaying error
                            'Add an error icon to the tray
                            .SubItems(1).Text = "Error"
                            For xInd As Int16 = 2 To 5
                                .SubItems(xInd).Text = ""
                            Next
                            .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                            .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                            .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                        End If
                    ElseIf Client.GuiController.ServiceState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eServiceState.Stopped Then
                        .ImageKey = "RED"
                        For xInd As Int16 = 1 To 5
                            .SubItems(xInd).Text = ""
                        Next
                        .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                        .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                        .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                    End If
                Else
                    If Client.GuiController.Running(True) Then
                        .ImageKey = "Green"
                        If Not Client.GuiController.Queue.HasError Then
                            If Client.GuiController.Queue.ActiveSlot.Status = "1" Then    'running
                                .SubItems(1).Text = Client.GuiController.Queue.ActiveSlot.Project.Project & "(R" & Client.GuiController.Queue.ActiveSlot.Project.Run & ", C" & Client.GuiController.Queue.ActiveSlot.Project.Gen & ", G" & Client.GuiController.Queue.ActiveSlot.Project.Gen & ")"
                                .SubItems(2).Text = Client.GuiController.Queue.CoreVersion
                                If Client.GuiController.Queue.Progress >= 0 Then
                                    .SubItems(3).Text = Client.GuiController.Queue.Progress
                                Else
                                    .SubItems(3).Text = " - "
                                End If
                                Dim strPPD As String = Client.GuiController.Queue.PPD_LastFrame.ToString
                                If Not strPPD = "0" Then
                                    If InStr(strPPD, ",") <> 0 Then
                                        Dim iDigits As Int16 = strPPD.Length - strPPD.LastIndexOf(",")
                                        For iAddDigits As Int16 = 4 To iDigits Step -1
                                            strPPD &= "0"
                                        Next
                                    Else
                                        strPPD &= ",0000"
                                    End If
                                    .SubItems(4).Text = strPPD
                                Else
                                    'Look for statistical data 
                                    If Not Client.GuiController.Statistics.ActivePRGC.KnownFrames = 0 Then
                                        'Use last frametime
                                        If ProjectInfo.KnownProject(Client.GuiController.Queue.ActiveSlot.Project.Project) Then
                                            strPPD = ProjectInfo.PPD(Client.GuiController.Queue.ActiveSlot.Project.Project, Client.GuiController.Statistics.ActivePRGC.AverageFrameTime).ToString
                                            If InStr(strPPD, ",") <> 0 Then
                                                Dim iDigits As Int16 = strPPD.Length - strPPD.LastIndexOf(",")
                                                For iAddDigits As Int16 = 4 To iDigits Step -1
                                                    strPPD &= "0"
                                                Next
                                            Else
                                                strPPD &= ",0000"
                                            End If
                                            .SubItems(4).Text = strPPD
                                        Else
                                            .SubItems(4).Text = strPPD
                                        End If
                                    Else
                                        'Look for reference values
                                        If Client.GuiController.Statistics.ActivePRGC.bHasReferenceValues Then
                                            'Use reference frame time
                                            strPPD = ProjectInfo.PPD(Client.GuiController.Queue.ActiveSlot.Project.Project, Client.GuiController.Statistics.ActivePRGC.rv3Frames).ToString
                                            If InStr(strPPD, ",") <> 0 Then
                                                Dim iDigits As Int16 = strPPD.Length - strPPD.LastIndexOf(",")
                                                For iAddDigits As Int16 = 4 To iDigits Step -1
                                                    strPPD &= "0"
                                                Next
                                            Else
                                                strPPD &= ",0000"
                                            End If
                                            .SubItems(4).Text = strPPD
                                        Else
                                            'Zero
                                            .SubItems(4).Text = strPPD
                                        End If
                                    End If
                                End If
                                If Client.GuiController.Queue.PPD_Effective <> -1 Then
                                    strPPD = Client.GuiController.Queue.PPD_Effective.ToString
                                    If InStr(strPPD, ",") <> 0 Then
                                        Dim iDigits As Int16 = strPPD.Length - strPPD.LastIndexOf(",")
                                        For iAddDigits As Int16 = 4 To iDigits Step -1
                                            strPPD &= "0"
                                        Next
                                    Else
                                        strPPD &= ",0000"
                                    End If
                                    .SubItems(5).Text = strPPD
                                Else
                                    .SubItems(5).Text = "0,0000"
                                End If
                                .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                            ElseIf Client.GuiController.Queue.ActiveSlot.Status = "2" Then 'Ready
                                .SubItems(1).Text = ""
                                .SubItems(2).Text = ""
                                .SubItems(3).Text = "Ready"
                                For yInd As Int16 = 4 To 5
                                    .SubItems(yInd).Text = ""
                                Next
                                .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                            ElseIf Client.GuiController.Queue.ActiveSlot.Status = "3" Then 'Downloading
                                .SubItems(1).Text = "Downloading"
                                For yInd As Int16 = 2 To 5
                                    .SubItems(yInd).Text = ""
                                Next
                                .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                            ElseIf Client.GuiController.Queue.ActiveSlot.Status = "0" Then 'Iddle
                                .ImageKey = "Yellow"
                                .SubItems(1).Text = "Idle"
                                For yInd As Int16 = 2 To 5
                                    .SubItems(yInd).Text = ""
                                Next
                                .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                                .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                                .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                            End If
                            If Not Client.PandeGroup.ServiceMode Then
                                Client.GuiController.IsService = False
                                If Client.GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Err Then
                                    .SubItems(9).Text = "Err"
                                ElseIf Client.GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Hidden Then
                                    .SubItems(9).Text = "-hidden-"
                                ElseIf Client.GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Visible Then
                                    .SubItems(9).Text = "-visible-"
                                Else
                                    MsgBox(Client.GuiController.wState)
                                End If
                            Else
                                Client.GuiController.IsService = True
                                Client.GuiController.AttachToSC()
                                Client.GuiController.StartWatching()
                                .SubItems(9).Text = ("-service-")
                            End If
                        End If
                    Else
                        .ImageKey = "Red"
                        For xInd As Int16 = 1 To 5
                            .SubItems(xInd).Text = ""
                        Next
                        .SubItems(6).Text = Client.GuiController.Queue.PointsInUpdate.ToString
                        .SubItems(7).Text = Client.GuiController.Queue.EUE_Count.ToString
                        .SubItems(8).Text = Client.GuiController.Queue.WUs_Ready.ToString
                        .SubItems(9).Text = ""
                    End If
                End If
            End With
            Dim iTPPD As Double = 0, iEPPD As Double = 0
            Try
                For xInd As Int16 = 0 To fTray.lvC.Items.Count - 1
                    If fTray.lvC.Items(xInd).SubItems(4).Text <> "" Then iTPPD += CDbl(fTray.lvC.Items(xInd).SubItems(4).Text)
                    If fTray.lvC.Items(xInd).SubItems(5).Text <> "" Then iEPPD += CDbl(fTray.lvC.Items(xInd).SubItems(5).Text)
                Next
                Math.Round(iTPPD, 4)
                Math.Round(iEPPD, 4)
                fTray.tsTotalPPD.Text = iTPPD.ToString & " (" & iEPPD.ToString & ")"
            Catch ex As Exception
            End Try
            'column content larger then width
            'tPB.Width = Me.ClientSize.Width - tsTime.Width - tsTotalPPD.Width - 100
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
#End Region

    Private Sub TestOptionsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TestOptionsToolStripMenuItem.Click
        frmOptions.ShowDialog(Me)
    End Sub

    Private Sub DebugToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DebugToolStripMenuItem.Click
        If LogWindow.IsWindowActive Then
            LogWindow.HideDebugWindow()
        Else
            LogWindow.ShowDebugWindow(clsLogwindow.TrayIcon.Log)
        End If
    End Sub

    Private Sub ResizeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ResizeToolStripMenuItem.Click
        Me.Visible = False
        For xInt As Int16 = 0 To 1
            Me.Size = sSize
            ResizeLVC()
            Prepare()
            SetFormSize()
        Next
        Me.Visible = True
    End Sub

    Private Sub mnuStopWhenDone_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuStopWhenDone.CheckedChanged
        If mnuStopWhenDone.Checked Then mnuStopOnFrame.Checked = False
        Application.DoEvents()
        For xInt As Int16 = 1 To Clients.Count - 1
            Clients(xInt).GuiController.CloseWhenUnitCompletes = mnuStopWhenDone.Checked
        Next
    End Sub

    Private Sub mnuStopOnFrame_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuStopOnFrame.CheckedChanged
        If mnuStopOnFrame.Checked Then mnuStopWhenDone.Checked = False
        Application.DoEvents()
        For xInt As Int16 = 1 To Clients.Count - 1
            Clients(xInt).GuiController.CloseWhenFrameCompletes = mnuStopOnFrame.Checked
        Next
    End Sub

    Private Sub mnuStatistics_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuStatistics.Click
        Try
            fStats.Show()
        Catch ex As Exception

        End Try
    End Sub
End Class

